/**
 * Copyright (c) 2020 Contributors to the Eclipse Foundation
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * https://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 */
package org.eclipse.vorto.repository.core.impl;

import org.eclipse.vorto.repository.core.IRepositoryManager;
import org.eclipse.vorto.repository.core.IUserContext;
import org.eclipse.vorto.repository.core.events.AppEvent;
import org.eclipse.vorto.repository.core.events.EventType;
import org.eclipse.vorto.repository.search.ISearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * The purpose of this class is to listen to EVENTS generated by other components for which an
 * action should be done on the repository
 */

@Component
public class ModelRepositoryEventListener implements ApplicationListener<AppEvent> {

  @Autowired
  private ModelRepositoryFactory repositoryFactory;

  @Autowired
  private ISearchService searchService;

  @Override
  public void onApplicationEvent(AppEvent event) {
    if (event.getEventType() == EventType.NAMESPACE_ADDED) {
      createWorkspace(event);
    }
  }

  private void createWorkspace(AppEvent event) {
    IUserContext userContext = event.getUserContext();
    IRepositoryManager repoMgr = repositoryFactory
        .getRepositoryManager(userContext.getWorkspaceId());
    repoMgr.createWorkspace(userContext.getWorkspaceId());
  }

  public ModelRepositoryFactory getRepositoryFactory() {
    return repositoryFactory;
  }

  public void setRepositoryFactory(ModelRepositoryFactory repositoryFactory) {
    this.repositoryFactory = repositoryFactory;
  }

  public ISearchService getSearchService() {
    return searchService;
  }

  public void setSearchService(ISearchService searchService) {
    this.searchService = searchService;
  }
}
